package frame.Good;

import MyBatis.MyBatislianjian;
import frame.Good.GoodPanel;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.CustomerMapper;
import org.example.mapper.GoodMapper;
import org.example.pojo.Customer;
import org.example.pojo.Good;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class goodadd extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private GoodMapper goodMapper = sqlSession.getMapper(GoodMapper.class);
    private CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);

    // 下拉框中的客户编号选项
    private JComboBox<String> cidComboBox;

    public goodadd() {
        // 设置内部窗口的标题和关闭方式
        setTitle("添加商品");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);

        // 添加表头
        String[] columnNames = {"商品编号", "商品名称", "商品价格", "客户编号", "商品介绍", "备注"};
        tableModel.setColumnIdentifiers(columnNames);

        // 添加一行空白数据
        addEmptyRow();

        // 设置表格可编辑
        table.setEnabled(true);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        JScrollPane scrollPane = new JScrollPane(table);

        // 将表格添加到内部窗口的中心区域
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 初始化客户编号下拉框
        cidComboBox = new JComboBox<>();
        populateCidComboBox(); // 填充客户编号下拉框

        // 将客户编号下拉框添加到表格的客户编号列
        TableColumn cidColumn = table.getColumnModel().getColumn(3); // 3是客户编号列的索引
        cidColumn.setCellEditor(new DefaultCellEditor(cidComboBox));

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 提示用户确认添加
                int confirm = JOptionPane.showConfirmDialog(goodadd.this, "确认添加表格中的所有商品数据到数据库？", "确认", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    // 提取表格数据并添加到数据库
                    List<Good> goodsToAdd = extractTableData();
                    if (goodsToAdd != null && !goodsToAdd.isEmpty()) {
                        boolean allValid = true;
                        Set<String> duplicateGids = new HashSet<>(); // 记录重复的商品编号
                        Set<String> nonExistingCids = new HashSet<>(); // 记录不存在的客户编号
                        for (Good good : goodsToAdd) {
                            // 检查关键字段不能为空
                            if (good.getGid().isEmpty() || good.getGName().isEmpty() || good.getGPay() == 0.0f || good.getCid().isEmpty()) {
                                allValid = false;
                                break;
                            }
                            // 检查商品编号是否存在数据库中
                            if (isGoodExists(good.getGid())) {
                                duplicateGids.add(good.getGid()); // 记录重复的商品编号
                            }
                            // 检查客户编号是否存在数据库中
                            if (!isCustomerExists(good.getCid())) {
                                nonExistingCids.add(good.getCid()); // 记录不存在的客户编号
                            }
                        }

                        if (allValid) {
                            if (duplicateGids.isEmpty() && nonExistingCids.isEmpty()) {
                                try {
                                    // 批量添加商品数据到数据库
                                    for (Good good : goodsToAdd) {
                                        goodMapper.addGood(good);
                                    }
                                    sqlSession.commit(); // 提交事务

                                    // 清空表格数据
                                    tableModel.setRowCount(0);
                                    addEmptyRow(); // 添加新的空行
                                    JOptionPane.showMessageDialog(goodadd.this, "成功添加 " + goodsToAdd.size() + " 条商品数据到数据库！", "提示", JOptionPane.INFORMATION_MESSAGE);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                    JOptionPane.showMessageDialog(goodadd.this, "添加商品数据时出现错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                                }
                            } else {
                                if (!duplicateGids.isEmpty()) {
                                    JOptionPane.showMessageDialog(goodadd.this, "表格中存在已经存在于数据库中的商品编号：" + duplicateGids, "错误", JOptionPane.ERROR_MESSAGE);
                                }
                                if (!nonExistingCids.isEmpty()) {
                                    JOptionPane.showMessageDialog(goodadd.this, "表格中存在不存在于数据库中的客户编号：" + nonExistingCids, "错误", JOptionPane.ERROR_MESSAGE);
                                }
                            }
                        } else {
                            JOptionPane.showMessageDialog(goodadd.this, "每一行的商品编号、商品名称、商品价格、客户编号都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(goodadd.this, "表格中没有数据可以添加！", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
        });

        // 添加手动添加商品按钮
        JButton manualAddButton = new JButton("添加商品行");
        manualAddButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 添加新的空白行
                addEmptyRow();
            }
        });

        // 返回按钮
        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new GoodPanel());
            }
        });

        // 将按钮添加到内部窗口的南部区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(addButton);
        buttonPanel.add(manualAddButton);
        buttonPanel.add(returnButton);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        // 设置内部窗口的大小和可见性
        setSize(800, 600);
        setVisible(true);
    }

    // 添加空白行到表格中
    private void addEmptyRow() {
        tableModel.addRow(new Object[]{"", "", "", "", "", ""});
    }

    // 提取表格数据的方法
    private List<Good> extractTableData() {
        List<Good> goods = new ArrayList<>();
        for (int row = 0; row < table.getRowCount(); row++) {
            String gid = (String) table.getValueAt(row, 0);
            String gName = (String) table.getValueAt(row, 1);
            String gPayStr = (String) table.getValueAt(row, 2);
            String cid = (String) table.getValueAt(row, 3);
            String gIntroduction = (String) table.getValueAt(row, 4);
            String other = (String) table.getValueAt(row, 5);

            // 检查商品编号、商品名称和客户编号是否为空
            if (gid.isEmpty() || gName.isEmpty() || cid.isEmpty()) {
                JOptionPane.showMessageDialog(goodadd.this, "每一行的商品编号、商品名称、客户编号都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                return null;
            }

            float gPay = 0.0f; // 默认值为0.0，可以根据需求修改为其他默认值或者提醒用户填写
            try {
                if (!gPayStr.isEmpty()) {
                    gPay = Float.parseFloat(gPayStr);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(goodadd.this, "商品价格字段必须是浮点数！", "错误", JOptionPane.ERROR_MESSAGE);
                return null;
            }

            // 创建 Good 对象并添加到列表
            Good good = new Good(gid, gName, gPay, cid, gIntroduction, other);
            goods.add(good);
        }
        return goods;
    }

    // 填充客户编号下拉框
    private void populateCidComboBox() {
        List<Customer> customers = customerMapper.selectAll(); // 获取所有客户
        for (Customer customer : customers) {
            cidComboBox.addItem(customer.getCid()); // 将客户编号添加到下拉框
        }
    }

    // 检查商品编号是否存在于数据库中
    private boolean isGoodExists(String gid) {
        Good good = goodMapper.selectGoodById(gid);
        return good != null;
    }

    // 检查客户编号是否存在于数据库中
    private boolean isCustomerExists(String cid) {
        Customer customer = customerMapper.selectByCid(cid);
        return customer != null;
    }
}
